package com.ll.gulimall.authserver.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ll.common.constant.AuthServerConstant;
import com.ll.common.utils.HttpUtils;
import com.ll.common.utils.R;
import com.ll.gulimall.authserver.feign.MemberFeignService;
import com.ll.common.vo.MemberEntityVo;
import com.ll.gulimall.authserver.vo.WeiBoResVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
/** 第三方社交登录
 * @author 21243
 */
public class AutoController {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/")
    public String weiboAuto(@RequestParam("code") String code, HttpSession session) throws Exception {

        //使用Code换取AccessCode
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3680331843");
        map.put("client_secret", "27404873667a784c048e1187c78e2c58");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/");
        map.put("code", code);
        //发送请求使用Code换取Access_toke 如果换取成功则登录成功
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
        if (response.getStatusLine().getStatusCode() == 200) {

            //获取请求结果字符串
            HttpEntity entity = response.getEntity();
            String json = EntityUtils.toString(entity);
            WeiBoResVo weiBoResVo = JSON.parseObject(json, WeiBoResVo.class);
            //调用远程服务执行登录
            R r = memberFeignService.login(weiBoResVo);
            if (r.getCode() == 0) {
                //远程调用成功
                MemberEntityVo memberEntity = r.getData(new TypeReference<MemberEntityVo>() {
                });
                log.info("用户登录成功,{}", memberEntity);
                // 解决Session子域  扩大Cookie作用域
                // 默认使用JKD序列化 如果使用JSON怎么办  注入自定义序列化
                session.setAttribute(AuthServerConstant.LOGIN_USER, memberEntity);
            } else {
                //登录失败
                return "redirect:http://auth.gulimall.com/";
            }
            //认真成功跳回首页
            return "redirect:http://gulimall.com";
        } else {
            //登录失败
            return "redirect:http://auth.gulimall.com/";
        }


    }
}
